import os
from pathlib import Path

from docx import Document

from base.RAG_da_bang.re_utils import re_anonymize_all


def scan_files(root_dir, extensions=None, max_depth=None):
    """
    递归扫描多层子目录中的文件
    :param root_dir: 根目录路径
    :param extensions: 允许的文件扩展名列表(如['.txt', '.csv'])，None表示所有文件
    :param max_depth: 最大扫描深度，None表示无限制
    :return: 文件路径生成器
    """
    root_path = Path(root_dir)
    if not root_path.exists():
        raise FileNotFoundError(f"目录不存在: {root_dir}")

    for item in root_path.rglob('*'):
        if not item.is_file():
            continue

        # 检查文件扩展名
        if extensions and item.suffix.lower() not in [ext.lower() for ext in extensions]:
            continue

        # 检查目录深度
        if max_depth is not None:
            depth = len(item.relative_to(root_path).parts) - 1
            if depth > max_depth:
                continue
        yield item.absolute()


def read_word(word_path):
    doc = Document(word_path)
    all_text = ''
    flag = False
    for para in doc.paragraphs:
        all_text = all_text + para.text
        re_text = re_anonymize_all(para.text)
        if re_text != para.text:
            print(re_text)
            para.text = re_text
            doc.save(word_path)
            flag = True
    if flag is not True:
        re_all_text = re_anonymize_all(all_text)
        if re_all_text != all_text:
            print('总体存在敏感信息')
            print(all_text)


if __name__ == '__main__':
    try:
        dir_path = r'D:\工作\IT公司RAG打榜比赛营销相关数据需求\china_mobile_docs_anonymize'
        exts = '.docx'
        extensions = [ext.strip() for ext in exts.split(',')] if exts else None
        print(extensions)

        print("\n扫描结果:")
        for idx, file in enumerate(scan_files(dir_path, extensions, max_depth=5), 1):
            print(f"{idx:>4}. {file}")
            try:
                read_word(file)
            except Exception as e:
                print(f"错误: {e}")
        # read_word(r'D:\工作\IT公司RAG打榜比赛营销相关数据需求\china_mobile_docs\云南\网格通常见问题解决建议.docx')
    except Exception as e:
        print(f"错误: {e}")
